<template>
  <div class="box">
    <el-form
      :model="user"
      :rules="rules"
      ref="loginForm"
      label-width="100px"
      class="demo-ruleForm box-right"
    >
      <!-- 用户名 -->
      <el-form-item label=" " prop="username">
        <span class="denglu">用户名</span>
        <el-input
          v-model="user.username"
          class="user"
          placeholder="请输入用户名"
        >
          <i slot="prefix" class="el-icon-user"></i>
        </el-input>
      </el-form-item>
      <!-- 密码 -->
      <el-form-item label=" " prop="password">
        <span class="denglu">密码</span>
        <el-input
          v-model="user.password"
          type="password"
          class="password"
          placeholder="请输入密码"
        >
          <i slot="prefix" class="el-icon-lock"></i>
        </el-input>
      </el-form-item>
      <!-- 验证码 -->
      <el-form-item label=" " prop="code">
        <span class="denglu">验证码</span>
        <div class="v-code">
          <el-input
            v-model="user.code"
            class="v-code-ipt"
            placeholder="请输入验证码"
          >
          </el-input>
          <div class="v-code-num" @click="loadCode()">
            <span v-for="b in code" :key="b" :style="{ color: getColors() }">
              {{ b }}</span
            >
          </div>
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handlerLogin" class="login"
          >登录</el-button
        >
        <br />
        <div class="reset">
          <el-link type="primary" @click="handlerReset">重置表单</el-link>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { loginApi, codeApi } from "@/Api/UserApi";
import { mapActions } from "vuex";
export default {
  data() {
    return {
      code: "",
      colors: ["red", "orange", "yellow", "green", "blue", "pink"],
      user: {
        username: "",
        password: "",
        code: "",
        captchaId: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
    };
  },
  mounted() {
    this.loadCode();
  },
  methods: {
    ...mapActions(["loadCurrentUserAction"]),
    getColors() {
      const index = Math.floor(Math.random() * this.colors.length);
      return this.colors[index];
    },
    //加载验证码
    async loadCode() {
      try {
        const res = await codeApi();
        console.log(res);
        if (res.status == 200) {
          this.code = res.data.code;
          this.user.code = this.code;
          this.user.captchaId = res.data.captchaId;
        } else {
          this.$message({
            message: res.msg,
            type: "error",
            duration: 1000,
          });
        }
      } catch (error) {
        console.log(error);
        this.$message({
          message: "系统异常",
          type: "error",
          duration: 1000,
        });
      }
    },
    handlerLogin() {
      this.$refs.loginForm
        .validate()
        .then(async () => {
          try {
            const res = await loginApi(this.user);

            if (res.status == 200) {
              //获取token值
              const token = res.data.token;
              //本地存储token
              localStorage.setItem("token", token);
              //通过用户输入获取token存储到本地vuex
              this.loadCurrentUserAction()
                .then(() => {
                  this.$message({
                    message: "登录成功",
                    type: "success",
                    duration: 1000,
                  });
                  this.$router.push({
                    path: "/main",
                  });
                })
                .catch((err) => {
                  console.log(err);

                  this.$message({
                    message: err.msg,
                    type: "error",
                    duration: 1000,
                  });
                  this.loadCode();
                });
            } else {
              this.$message({
                message: res.msg,
                type: "error",
                duration: 1000,
              });
              this.loadCode();
            }
          } catch (error) {
            this.$message({
              message: "系统异常",
              type: "error",
              duration: 1000,
            });
            this.loadCode();
          }
        })
        .catch((error) => {
          this.$message({
            message: "登录失败",
            type: "error",
            duration: 1000,
          });
          this.loadCode();
        });
    },
    handlerReset() {
      this.user.username = "";
      this.user.password = "";
      this.user.code = "";
    },
  },
};
</script>

<style lang="less" scoped>
.denglu {
  font-size: 16px;
  font-weight: 100;

  color: #f0f2f4;
}
.box {
  width: 100vw;
  height: 100vh;
  display: flex;
  background-image: url(../assets/img/m8.jpg);
  background-size: cover; /* 缩放图片以填满容器，可能裁剪 */
  background-position: center center; /* 图片居中，避免偏移 */
  background-repeat: no-repeat; /* 禁止重复 */
  background-attachment: fixed; /* 可选：固定背景不随滚动移动 */
  &-right {
    width: 500px;
    height: 400px;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
  }
}

.reset {
  width: 400px;
  display: flex;
  justify-content: center;
}
.login {
  width: 400px;
}

.user {
  width: 400px;
}
.password {
  width: 400px;
}
.v-code {
  display: flex;
  &-ipt {
    width: 200px;
  }
  &-num {
    width: 100px;
    background-color: #f0f2f4;
    border-radius: 5px;
    margin-left: 5px;
    line-height: 40px;
    text-align: center;
    span {
      font-size: 18px;
      font-weight: 600;
    }
  }
}
</style>